package com.joysuch.wwyt.attendance.service.impl;


import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.collect.Lists;
import com.joysuch.wwyt.attendance.bean.*;
import com.joysuch.wwyt.attendance.dto.AttendanceGroupShiftDto;
import com.joysuch.wwyt.attendance.dto.AttendanceUserDto;
import com.joysuch.wwyt.attendance.entity.AttendanceGroup;
import com.joysuch.wwyt.attendance.entity.AttendanceShift;
import com.joysuch.wwyt.attendance.entity.AttendanceUser;
import com.joysuch.wwyt.attendance.enums.AttendanceFlagEnum;
import com.joysuch.wwyt.attendance.mapper.AttendanceGroupMapper;
import com.joysuch.wwyt.attendance.mapper.AttendanceShiftMapper;
import com.joysuch.wwyt.attendance.mapper.AttendanceUserMapper;
import com.joysuch.wwyt.attendance.service.AttendanceGroupService;
import com.joysuch.wwyt.attendance.service.AttendanceUserService;
import com.joysuch.wwyt.attendance.util.AttendanceDayUtils;
import com.joysuch.wwyt.bp.entity.BpDepart;
import com.joysuch.wwyt.bp.repository.BpDepartDao;
import com.joysuch.wwyt.bp.service.BpDepartService;
import com.joysuch.wwyt.core.bean.SimpleListBean;
import com.joysuch.wwyt.core.entity.BaseUser;
import com.joysuch.wwyt.core.enums.DeleteFlag;
import com.joysuch.wwyt.core.enums.Status;
import com.joysuch.wwyt.core.exception.ApiBusinessException;
import com.joysuch.wwyt.core.repository.BaseUserDao;
import com.joysuch.wwyt.core.support.Context;
import com.joysuch.wwyt.util.PageableUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author zqw
 * @since 2022-03-03
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class AttendanceUserServiceImpl extends ServiceImpl<AttendanceUserMapper, AttendanceUser> implements AttendanceUserService {

    @Autowired
    private AttendanceUserService userService;

    @Autowired
    private AttendanceUserMapper userMapper;

    @Autowired
    private AttendanceGroupService groupService;

    @Autowired
    private AttendanceGroupMapper groupMapper;

    @Autowired
    private BaseUserDao baseUserDao;

    @Autowired
    private BpDepartDao bpDepartDao;

    @Autowired
    private BpDepartService bpDepartService;

    @Autowired
    private AttendanceShiftMapper shiftMapper;


    @Override
    public void saveFixTask(Integer year, Integer month) {
        createUserTask(Context.getCompanyCode(), Context.getCurrentTenantId(), year, month);
    }

    @Override
    public void createUserTask(String orgCode, Long tenentId, Integer year, Integer month) {
        //获取固定排班的考勤组
        List<AttendanceGroup> groupList = groupService.getGroupByAttendanceFlag(AttendanceFlagEnum.FIXED.getValue(), orgCode, tenentId);
        if (!CollectionUtils.isEmpty(groupList)) {
            //获取下个月-年月日周集合
            List<AttendanceDayBean> dayBeans = AttendanceDayUtils.getDayByMonth(year, month + 1);
            List<Long> groupIds = groupList.stream().map(AttendanceGroup::getId).distinct().collect(Collectors.toList());
            //获取已经排过班的人员
            List<AttendanceUser> oldUsers = userMapper.getUsersByGroupIds(groupIds, dayBeans.get(0).getYear(), dayBeans.get(0).getMonth());
            List<AttendanceUser> userList = new ArrayList<>();
            for (AttendanceGroup group : groupList) {
                userList = saveFixUserTask(group.getId(), userList, oldUsers, group.getAttendanceJson(), group.getParticipantIds(), group.getParticipantType(), dayBeans, 0);
            }
            if (!CollectionUtils.isEmpty(userList)) {
                userService.saveBatch(userList);
            }
        }
    }

    @Override
    public AttendanceUserPageBean pageUserTask(AttendanceUserParam pageParam) {
        boolean userFlag = AttendanceDayUtils.getDateCheckFlag(pageParam.getYear(), pageParam.getMonth());
        List<AttendanceDayBean> dayBeans = AttendanceDayUtils.getDayByMonth(pageParam.getYear(), pageParam.getMonth());
        AttendanceUserPageBean pBean = new AttendanceUserPageBean();
        AttendanceGroup group = groupMapper.selectById(pageParam.getGroupId());
        if (group == null) {
            return pBean;
        }
        if (StringUtils.isBlank(group.getParticipantIds())) {
            return null;
        }
        if (userFlag) {
            pBean = getNewUserPageBean(pBean, pageParam, dayBeans, group);
        } else {
            pBean = getOldUserPageBean(pBean, pageParam, dayBeans, group);
        }

        return pBean;
    }

    private AttendanceUserPageBean getNewUserPageBean(AttendanceUserPageBean pBean, AttendanceUserParam pageParam, List<AttendanceDayBean> dayBeans, AttendanceGroup group) {

        List<BaseUser> users = getGroupStaffList(group, pageParam.getDepartId(), pageParam.getUserName());
        pBean.setTotalCount(users.size());
        List<AttendanceUser> attendanceUsers = new ArrayList<>();
        //对人员分页
        List<BaseUser> resultUsers = PageableUtil.getList(pageParam.getPageNumber(), pageParam.getPageSize(), users);
        //超过分页上限 则立即返回
        if (!CollectionUtils.isEmpty(resultUsers)) {
            List<Long> resultUserIds = resultUsers.stream().map(BaseUser::getId).distinct().collect(Collectors.toList());
            List<Long> departIds = resultUsers.stream().map(BaseUser::getDepartId).distinct().collect(Collectors.toList());
            Map<Long, BpDepart> departMap = bpDepartService.getDepartMapByIds(departIds);
            attendanceUsers = userMapper.selectByStaffsAndGroupIdAndYearAndMonth(resultUserIds, pageParam.getGroupId(), pageParam.getYear(), pageParam.getMonth());
            //人员排班集合
            List<AttenUserDateBean> userDateBeanList = covertUserDateBeanList(attendanceUsers, resultUsers, departMap, dayBeans, group.getId());
            pBean.setUserDateBeanList(userDateBeanList);
        }
        //班次汇总集合
        List<Long> resultUserIds = users.stream().map(BaseUser::getId).distinct().collect(Collectors.toList());
        if (!CollectionUtils.isEmpty(resultUserIds)) {
            attendanceUsers = userMapper.selectByStaffsAndGroupIdAndYearAndMonth(resultUserIds, pageParam.getGroupId(), pageParam.getYear(), pageParam.getMonth());
        } else {
            attendanceUsers = new ArrayList<>();
        }
        List<AttenShiftDateBean> shiftDateBeanList = convertShiftDateBeanList(attendanceUsers, dayBeans, group);
        pBean.setShiftDateBeanList(shiftDateBeanList);

        return pBean;
    }

    private AttendanceUserPageBean getOldUserPageBean(AttendanceUserPageBean pBean, AttendanceUserParam pageParam, List<AttendanceDayBean> dayBeans, AttendanceGroup group) {
        List<AttendanceUser> users = userMapper.selectByGroupIdAndYearAndMonthAndUserNameAndDepartId(pageParam.getGroupId(), pageParam.getYear(), pageParam.getMonth(), pageParam.getUserName(), pageParam.getDepartId());
        List<AttendanceUser> attendanceUsers = new ArrayList<>();
        if (!CollectionUtils.isEmpty(users)) {
            Map<Long, List<AttendanceUser>> userMap = users.stream().collect(Collectors.groupingBy(e -> e.getUserId()));
            List<Long> userIds = users.stream().map(AttendanceUser::getUserId).distinct().collect(Collectors.toList());
            pBean.setTotalCount(userMap.size());
            List<Long> userIdList = PageableUtil.getList(pageParam.getPageNumber(), pageParam.getPageSize(), userIds);
            List<BaseUser> baseUsers = baseUserDao.getUsersByIds(userIdList);
            if (!CollectionUtils.isEmpty(userIdList)) {
                List<Long> departIds = baseUsers.stream().map(BaseUser::getDepartId).collect(Collectors.toList());
                List<BpDepart> departList = bpDepartDao.findByIds(departIds);
                Map<Long, BpDepart> departMap = departList.stream().collect(Collectors.toMap(d -> d.getId(), e -> e));
                for (Map.Entry<Long, List<AttendanceUser>> entry : userMap.entrySet()) {
                    for (Long u : userIdList) {
                        if (u.equals(entry.getKey())) {
                            attendanceUsers.addAll(entry.getValue());
                        }
                    }
                }
                //人员排班集合
                List<AttenUserDateBean> userDateBeanList = covertUserDateBeanList(attendanceUsers, baseUsers, departMap, dayBeans, group.getId());
                pBean.setUserDateBeanList(userDateBeanList);
            }
        }
        //班次汇总集合
        List<AttenShiftDateBean> shiftDateBeanList = convertShiftDateBeanList(users, dayBeans, group);
        pBean.setShiftDateBeanList(shiftDateBeanList);
        return pBean;
    }

    private List<AttenUserDateBean> getNullUserDateBean(List<AttendanceDayBean> dayBeans) {
        List<AttenUserDateBean> userDateBeanList = new ArrayList<>();
        AttenUserDateBean dateBean = new AttenUserDateBean();
        List<AttendanceUserDayBean> userDayBeanList = new ArrayList<>();
        dayBeans.forEach(d -> {
            AttendanceUserDayBean userDayBean = new AttendanceUserDayBean();
            userDayBean.setWeekDay(d.getWeekDay());
            userDayBean.setDay(d.getDay());
            userDayBeanList.add(userDayBean);
        });
        dateBean.setUserDayBeanList(userDayBeanList);
        userDateBeanList.add(dateBean);
        return userDateBeanList;
    }

    private List<AttenUserDateBean> covertUserDateBeanList(List<AttendanceUser> attendanceUsers, List<BaseUser> baseUsers, Map<Long, BpDepart> departMap, List<AttendanceDayBean> dayBeans, Long groupId) {
        Map<String, List<AttendanceUser>> attendanceUserMap = new HashMap<>();
        Map<Long, AttendanceShift> shiftMap = new HashMap<>();
        if (!CollectionUtils.isEmpty(attendanceUsers)) {
            List<Long> shiftIds = attendanceUsers.stream().map(AttendanceUser::getShiftId).distinct().collect(Collectors.toList());
            List<AttendanceShift> shifts = shiftMapper.selectBatchIds(shiftIds);
            attendanceUserMap = attendanceUsers.stream().collect(Collectors.groupingBy(r -> getKey(r.getGroupId(), r.getUserId(), r.getAttendanceDay())));
            if (!CollectionUtils.isEmpty(shifts)) {
                shiftMap = shifts.stream().collect(Collectors.toMap(AttendanceShift::getId, e -> e));
            }
        }
        List<AttenUserDateBean> userDateBeanList = new ArrayList<>();
        for (BaseUser u : baseUsers) {
            AttenUserDateBean attenUserDateBean = new AttenUserDateBean();
            //人员部门信息
            attenUserDateBean.setUserId(u.getId());
            attenUserDateBean.setUserName(u.getRealName());
            attenUserDateBean.setDepartId(u.getDepartId());
            if (departMap.get(u.getDepartId()) != null) {
                attenUserDateBean.setDepartName(departMap.get(u.getDepartId()).getName());
            }
            List<AttendanceUserDayBean> userDayBeanList = new ArrayList<>();
            //排班集合
            for (AttendanceDayBean dayBean : dayBeans) {
                AttendanceUserDayBean attendanceUserDayBean = new AttendanceUserDayBean();
                attendanceUserDayBean.setDay(dayBean.getDay());
                attendanceUserDayBean.setWeekDay(dayBean.getWeekDay());
                List<AttendanceUser> dayUserList = attendanceUserMap.get(getKey(groupId, u.getId(), dayBean.getDay()));
                if (!CollectionUtils.isEmpty(dayUserList)) {
                    List<AttendanceUserDayShifBean> dayShiftList = new ArrayList<>();
                    for (AttendanceUser au : dayUserList) {
                        AttendanceUserDayShifBean shifBean = new AttendanceUserDayShifBean();
                        shifBean.setId(au.getShiftId());
                        AttendanceShift shift = shiftMap.get(au.getShiftId());
                        shifBean.setName(shift.getShiftName());
                        shifBean.setBreakFlag(shift.getBreakFlag());
                        dayShiftList.add(shifBean);
                    }
                    attendanceUserDayBean.setDayShiftList(dayShiftList);
                }
                userDayBeanList.add(attendanceUserDayBean);
            }
            attenUserDateBean.setUserDayBeanList(userDayBeanList);
            userDateBeanList.add(attenUserDateBean);
        }
        return userDateBeanList;
    }

    private List<AttenShiftDateBean> convertShiftDateBeanList(List<AttendanceUser> attendanceUsers, List<AttendanceDayBean> dayBeans, AttendanceGroup group) {
        List<AttenShiftDateBean> shiftDateBeanList = new ArrayList<>();
        List<AttendanceShift> shiftList = groupService.getGroupShiftList(group);
        if (CollectionUtils.isEmpty(shiftList)) {
            return shiftDateBeanList;
        }
        Map<String, List<AttendanceUser>> shiftCountMap = new HashMap<>();
        if (!CollectionUtils.isEmpty(attendanceUsers)) {
            shiftCountMap = attendanceUsers.stream().collect(Collectors.groupingBy(r -> getKey(r.getGroupId(), r.getShiftId(), r.getAttendanceDay())));
        }
        for (AttendanceShift shift : shiftList) {
            AttenShiftDateBean shiftDateBean = new AttenShiftDateBean();
            shiftDateBean.setShiftId(shift.getId());
            shiftDateBean.setShiftName(shift.getShiftName());
            List<AttendanceShiftDayBean> shiftDayBeanList = new ArrayList<>();
            for (AttendanceDayBean dayBean : dayBeans) {
                AttendanceShiftDayBean attendanceShiftDayBean = new AttendanceShiftDayBean();
                attendanceShiftDayBean.setDay(dayBean.getDay());
                attendanceShiftDayBean.setWeekDay(dayBean.getWeekDay());
                String key = getKey(group.getId(), shift.getId(), dayBean.getDay());
                if (CollectionUtils.isEmpty(shiftCountMap.get(key))) {
                    attendanceShiftDayBean.setCount(0);
                } else {
                    attendanceShiftDayBean.setCount(shiftCountMap.get(key).size());
                }
                shiftDayBeanList.add(attendanceShiftDayBean);
            }
            shiftDateBean.setShiftDayBeanList(shiftDayBeanList);
            shiftDateBeanList.add(shiftDateBean);
        }
        return shiftDateBeanList;
    }

    @Override
    public List<BaseUser> getGroupStaffList(AttendanceGroup group, Long departId, String userName) {
        Integer parType = group.getParticipantType();
        List<BaseUser> users = new ArrayList<>();
        String parJson = group.getParticipantIds();
        List<Long> parIds = JSONArray.parseArray(parJson, Long.class);
        if (parType.intValue() == 0) {
            users = baseUserDao.getUsersByIdsAndDepartIdAndUserName(parIds, departId, userName);
        } else if (parType.intValue() == 1) {
            if (departId != null) {
                if (parIds.contains(departId)) {
                    parIds = Lists.newArrayList(departId);
                } else {
                    return users;
                }
            }
            users = baseUserDao.getUsersByDepartIds(parIds, userName);
        } else if (parType.intValue() == 2) {
            users = baseUserDao.getUsersByJobIdsAndDepartIdAndUserName(parIds, departId, userName);
        }
        return users;
    }

    @Override
    public List<AttendanceUser> getAttendanceUserByGroupAndYearAndMonth(Long groupId, int year, int month) {
        return userMapper.selectUsersByGroupIdAndYearAndMonth(groupId, year, month);
    }

    @Override
    public void saveUserTask(AttendanceUserDto dto) throws ApiBusinessException {
        List<AttendanceUser> userList = new ArrayList<>();
        if (dto.getFlag().intValue() == 1) {
            //排班制考勤->从当天开始 本月排班按照排班制考勤从新排班
            userList = convertPeriodUserTask(dto);
            if (!CollectionUtils.isEmpty(userList)) {
                userService.saveOrUpdateBatch(userList);
            }
        } else {
            List<AttendanceUser> oldUserList = userMapper.selectUsersByDayAndUserId(dto.getGroupId(), dto.getAttendanceYear(), dto.getAttendanceMonth(), dto.getAttendanceDay(), dto.getUserId());
            //新增/修改/删除
            userList = convertUserThatDayData(userList, oldUserList, dto.getShiftIds(), dto.getGroupId(), dto.getUserId(), dto.getAttendanceYear(), dto.getAttendanceMonth(), dto.getAttendanceDay(), dto.getAttendanceWeek(), AttendanceFlagEnum.CUSTOMIZE.getValue());

        }
        if (!CollectionUtils.isEmpty(userList)) {
            userService.saveOrUpdateBatch(userList);
        }
    }

    //排班制考勤
    private List<AttendanceUser> convertPeriodUserTask(AttendanceUserDto dto) throws ApiBusinessException {
        List<AttendanceUser> userList = new ArrayList<>();
        AttendanceGroup group = groupMapper.selectById(dto.getGroupId());
        if (group == null) {
            throw new ApiBusinessException(Status.ATTENDANCE_GROUP_NOT_EXIST);
        }
        if (group.getAttendanceFlag().intValue() == 0) {
            throw new ApiBusinessException(Status.ATTENDANCE_GROUP_TYPE_ERROR);
        }
        if (StringUtils.isBlank(group.getAttendanceJson())) {
            return userList;
        }
        List<AttendanceGroupShiftDto> shiftDtos = JSONArray.parseArray(group.getAttendanceJson(), AttendanceGroupShiftDto.class);
        Map<String, AttendanceGroupShiftDto> groupShiftMap = shiftDtos.stream().collect(Collectors.toMap(AttendanceGroupShiftDto::getSerialNumber, e -> e));
        //获取该人员本月剩余排班
        List<AttendanceDayBean> dayBeans = AttendanceDayUtils.getDayByMonth(dto.getAttendanceYear(), dto.getAttendanceMonth());
        dayBeans = dayBeans.stream().filter(e -> (e.getDay() >= dto.getAttendanceDay())).collect(Collectors.toList());
        //按照排班制考勤分组
        List<List<AttendanceDayBean>> groupBeanList = PageableUtil.groupByList(dayBeans, shiftDtos.size());
        //获取该人员本月剩余已经排好的班
        List<AttendanceUser> remUsers = userMapper.getRemainingThisMonth(dto.getGroupId(), dto.getAttendanceYear(), dto.getAttendanceMonth(), dto.getAttendanceDay() - 1, dto.getUserId());
        Map<Integer, List<AttendanceUser>> remUserMap = remUsers.stream().collect(Collectors.groupingBy(AttendanceUser::getAttendanceDay));
        for (List<AttendanceDayBean> beanList : groupBeanList) {
            for (int i = 0; i < beanList.size(); i++) {
                AttendanceDayBean dayBean = beanList.get(i);
                List<AttendanceUser> auList = remUserMap.get(dayBean.getDay());
                AttendanceGroupShiftDto gfDto = groupShiftMap.get("第" + (i + 1) + "天");
                userList = convertUserThatDayData(userList, auList, gfDto.getShiftList(), dto.getGroupId(),
                        dto.getUserId(), dayBean.getYear(), dayBean.getMonth(), dayBean.getDay(), dayBean.getWeekDay(), AttendanceFlagEnum.PERIOD.getValue());
            }
        }
        return userList;
    }

    /**
     * 处理人员当天排班信息
     *
     * @param userList       返回信息
     * @param oldUserDayList 当天人员已经拍好的排班休息
     * @param dayShiftIds    当天的排版集合
     * @param groupId        考勤组id
     * @param userId         人员id
     * @param year
     * @param month
     * @param day
     * @param weekDay
     * @param attendanceFlag 人员排班类型
     * @return userList
     */
    private List<AttendanceUser> convertUserThatDayData(List<AttendanceUser> userList, List<AttendanceUser> oldUserDayList, List<Long> dayShiftIds,
                                                       Long groupId, Long userId, Integer year, Integer month, Integer day, String weekDay, Integer attendanceFlag) {
        Map<Long, AttendanceUser> shiftUserMap = new HashMap<>();
        if (!CollectionUtils.isEmpty(oldUserDayList)) {
            shiftUserMap = oldUserDayList.stream().collect(Collectors.toMap(AttendanceUser::getShiftId, e -> e));
        }
        if (CollectionUtils.isEmpty(dayShiftIds)) {
            return userList;
        }
        for (Long shiftId : dayShiftIds) {
            //存在的修改,不存在新增
            AttendanceUser u = new AttendanceUser();
            if (shiftUserMap.get(shiftId) != null) {
                u = shiftUserMap.get(shiftId);
            }
            u.setGroupId(groupId);
            u.setShiftId(shiftId);
            u.setUserId(userId);
            u.setAttendanceYear(year);
            u.setAttendanceMonth(month);
            u.setAttendanceDay(day);
            u.setAttendanceWeek(weekDay);
            u.setAttendanceFlag(attendanceFlag);
            userList.add(u);
        }
        //如果该天已经存在的班次在班组排班中没有,删除
        for (Long deleteShiftId : shiftUserMap.keySet()) {
            if (!dayShiftIds.contains(deleteShiftId)) {
                AttendanceUser user = shiftUserMap.get(deleteShiftId);
                user.setDeleteFlag(DeleteFlag.DELETED.getCode());
                userList.add(user);
            }
        }
        return userList;
    }

    @Override
    public List<AttendanceUser> saveFixUserTask(Long groupId, List<AttendanceUser> userList, List<AttendanceUser> oldUsers, String attendanceJson, String participantIds, Integer participantType, List<AttendanceDayBean> dayBeans, Integer renewFlag) {
        if (StringUtils.isBlank(attendanceJson) || StringUtils.isBlank(participantIds) || CollectionUtils.isEmpty(dayBeans)) {
            return userList;
        }
        List<Long> userIds = new ArrayList<>();
        List<AttendanceGroupShiftDto> shiftDtos = JSONArray.parseArray(attendanceJson, AttendanceGroupShiftDto.class);
        List<Long> parIds = JSONArray.parseArray(participantIds, Long.class);
        if (participantType.intValue() == 0) {
            //人员
            userIds.addAll(parIds);
        } else if (participantType.intValue() == 1) {
            //班组
            userIds.addAll(baseUserDao.getUserIdsByDepartIds(parIds));
        } else if (participantType.intValue() == 2) {
            //岗位
            userIds.addAll(baseUserDao.getUserIdsByJobIds(parIds));
        }
        return convertFixUserTask(userList, groupId, dayBeans, shiftDtos, userIds, oldUsers, Context.getCompanyCode(), Context.getCurrentTenantId(), renewFlag);
    }

    private List<AttendanceUser> convertFixUserTask(List<AttendanceUser> userList, Long groupId, List<AttendanceDayBean> dayBeans, List<AttendanceGroupShiftDto> shiftDtos, List<Long> userIds, List<AttendanceUser> oldUsers, String orgCode, Long tenentId, Integer renewFlag) {
        //按照当天所在周分组
        Map<String, AttendanceGroupShiftDto> shiftMap = shiftDtos.stream().collect(Collectors.toMap(AttendanceGroupShiftDto::getSerialNumber, e -> e));
        Map<String, List<AttendanceUser>> oldUserMap = oldUsers.stream().collect(Collectors.groupingBy(r -> getKey(r.getGroupId(), r.getUserId(), r.getAttendanceDay())));
        Map<String, List<AttendanceUser>> oldUserDayShiftMap = oldUsers.stream().collect(Collectors.groupingBy(r -> getUserDayShiftKey(r.getGroupId(), r.getUserId(), r.getAttendanceDay(), r.getShiftId())));
        Map<String, AttendanceUser> newUserDayShiftMap = new HashMap<>();
        dayBeans.forEach(day -> {
            String weekDay = day.getWeekDay();
            for (Long userId : userIds) {
                AttendanceGroupShiftDto dto = shiftMap.get(weekDay);
                if (dto == null || CollectionUtils.isEmpty(dto.getShiftList())) {
                    continue;
                }
                if (renewFlag.intValue() == 0) {
                    //人员已经设置过排班的,定时任务不再设置
                    if (CollectionUtils.isEmpty(oldUserMap.get(getKey(groupId, userId, day.getDay())))) {
                        for (Long shiftId : dto.getShiftList()) {
                            AttendanceUser user = new AttendanceUser(null, userId, groupId, shiftId, day.getWeekDay(), day.getYear(), day.getMonth(), day.getDay(), AttendanceFlagEnum.FIXED.getValue());
                            user.setOrgCode(orgCode);
                            user.setTenentId(tenentId);
                            userList.add(user);
                        }
                    }
                } else if (renewFlag.intValue() == 1) {
                    for (Long shiftId : dto.getShiftList()) {
                        String userDayShiftKey = getUserDayShiftKey(groupId, userId, day.getDay(), shiftId);
                        AttendanceUser u = new AttendanceUser();
                        if (!CollectionUtils.isEmpty(oldUserDayShiftMap.get(userDayShiftKey))) {
                            u = oldUserDayShiftMap.get(userDayShiftKey).get(0);
                        }
                        u.setGroupId(groupId);
                        u.setShiftId(shiftId);
                        u.setUserId(userId);
                        u.setAttendanceYear(day.getYear());
                        u.setAttendanceMonth(day.getMonth());
                        u.setAttendanceDay(day.getDay());
                        u.setAttendanceWeek(day.getWeekDay());
                        u.setAttendanceFlag(AttendanceFlagEnum.FIXED.getValue());
                        u.setOrgCode(orgCode);
                        u.setTenentId(tenentId);
                        userList.add(u);
                        newUserDayShiftMap.put(userDayShiftKey, u);
                    }
                }
            }
        });
        //删除不需要的人员排班
        if (renewFlag.intValue() == 1 && !CollectionUtils.isEmpty(oldUserDayShiftMap)) {
            for (Map.Entry<String, List<AttendanceUser>> oldEntry : oldUserDayShiftMap.entrySet()) {
                if (newUserDayShiftMap.get(oldEntry.getKey()) == null) {
                    AttendanceUser oldUser = oldEntry.getValue().get(0);
                    oldUser.setDeleteFlag(DeleteFlag.DELETED.getCode());
                    userList.add(oldUser);
                }
            }
        }
        return userList;
    }

    private String getKey(Long groupId, Long userId, Integer day) {
        return groupId + "-" + userId + "-" + day;
    }

    private String getUserDayShiftKey(Long groupId, Long userId, Integer day, Long shiftId) {
        return groupId + "-" + userId + "-" + day + "-" + shiftId;
    }


}
